﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace planerka.Common
{

    public class graphics
    {

        public graphics()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        //

        public static bool savePicture(
            string fileNameAndPath,
            string savePathAndName,
            int resizeWidth,  // - ограничить по ширине, если больше - resize
            int resizeHeight, // -то же. Если resizeHeight = 0, то оставляем как есть
            long encodingQuality, // качество компрессии для графических файлов
            //bool addWatermark,
            ref string resMessage
            )
        {
            // http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.fileupload.aspx
            // http://www.eggheadcafe.com/articles/20030706.asp
            // http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

            if (System.IO.File.Exists(fileNameAndPath))//  iFileUpload_picture.HasFile)
            {
                // Get the extension of the uploaded file.
                string extension = System.IO.Path.GetExtension(fileNameAndPath);
                FileInfo finfo = new FileInfo(fileNameAndPath);

                // PRESERVE!!!
                /*
                long fileSize = finfo.Length;// iFileUpload_picture.PostedFile.ContentLength;

                // Allow only files less than 4,300,000 bytes (approximately 4 MB) to be uploaded.
                if (fileSize > 4300000)
                {
                    resMessage = "Файл слишком большой";

                    return false;
                }
                */

                // Allow only files with .doc or .xls extensions
                // to be uploaded.
                if ((extension == ".jpg") | (extension == ".png") | (extension == ".gif") | (extension == ".jpeg") |
                     (extension == ".JPEG") | (extension == ".JPG") | (extension == ".PNG") | (extension == ".GIF"))
                {

                    System.Drawing.Image imgToResize = System.Drawing.Image.FromFile(fileNameAndPath);

                    int height = (int)(resizeWidth *
                         ((double)imgToResize.Height / (double)imgToResize.Width));

                    // Create an Encoder object based on the GUID
                    // for the Quality parameter category.
                    ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

                    System.Drawing.Imaging.Encoder myEncoder =
                        System.Drawing.Imaging.Encoder.Quality;

                    // Create an EncoderParameters object.
                    // An EncoderParameters object has an array of EncoderParameter
                    // objects. In this case, there is only one
                    // EncoderParameter object in the array.
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);

                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Convert.ToInt64(encodingQuality));
                    myEncoderParameters.Param[0] = myEncoderParameter;


                    // сохраним начальное изображение

                    int heightFull = (int)imgToResize.Height;
                    int widthFull = (int)imgToResize.Width;

                    if ((double)imgToResize.Width > resizeWidth)
                    {
                        // в таком случае сразу обрежем начальное изображение
                        // к тому же это экономит место на сервере

                        heightFull = (int)(resizeWidth *
                         ((double)imgToResize.Height / (double)imgToResize.Width));

                        widthFull = resizeWidth;


                        if (resizeHeight != 0)
                        {
                            if ((double)heightFull > resizeHeight)
                            {
                                // тогда более приоритетной считается обрезка по высоте
                                //       heightFull = (int)(resizeWidth *
                                //((double)imgToResize.Height / (double)imgToResize.Width));

                                widthFull = (int)(resizeHeight *
                                    ((double)imgToResize.Width / (double)imgToResize.Height));

                                heightFull = resizeHeight;
                            }
                        }


                    }

                    System.Drawing.Image fullImage = resizeImage(imgToResize, widthFull, heightFull);

                    /*
                    if (addWatermark)
                    {
                        // добавим водяной знак
                        string pathToWatermark = HttpContext.Current.Server.MapPath("~/Content/images/" + System.Configuration.ConfigurationManager.AppSettings["watermark"]);
                        Graphics oGraphics;

                        oGraphics = Graphics.FromImage(fullImage);
                        oGraphics.DrawImage(fullImage, 0, 0);


                        Bitmap objImage = new Bitmap(pathToWatermark);
                        //ImageAttributes ia = new ImageAttributes();

                        oGraphics.DrawImage(objImage, 20, 20);
                    }*/

                    fullImage.Save(savePathAndName, jgpEncoder, myEncoderParameters);
                    fullImage.Dispose();
                    fullImage = null;

                    return true;
                }
                else
                {
                    // Notify the user why their file was not uploaded.
                    resMessage = "Файл не был загружен из-за несоответствия формата";
                    return false;
                }
            }
            else
            {
                resMessage = "Укажите путь к картинке";
                return false;

            }
        }

        //
        public static System.Drawing.Image resizeImage(
            System.Drawing.Image imgToResize,
            int newWidth,
            int newHeight
            )
        {
            Bitmap b = new Bitmap(newWidth, newHeight);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, newWidth, newHeight);
            g.Dispose();

            return (System.Drawing.Image)b;
        }

        //

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

       // очистить temp-директорию
        public static void emptyDirectory(string absolutePath)
        {
            string directory = absolutePath;
            // System.Web.HttpContext.Current.Server.MapPath("~/images/temp/");
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(directory);
            // Get a reference to each file in that directory.
            System.IO.FileInfo[] fiArr = di.GetFiles();

            foreach (System.IO.FileInfo finfo in fiArr)
            {
                try { System.IO.File.Delete(finfo.FullName); }  catch { }
            }
        }
       
    }

}